package com.ruoyi.web.controller.combat.equiplocation;

import cn.hutool.core.io.resource.ResourceUtil;
import com.ruoyi.combat.domain.equiplocation.CombatEquipInfo;
import com.ruoyi.combat.domain.equiplocation.CombatFakeIp;
import com.ruoyi.combat.domain.position.AntiPositioningInfo;
import com.ruoyi.combat.domain.request.AntiAttributionCallbackRequest;
import com.ruoyi.combat.service.equiplocation.ICombatEquipInfoService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * 网络IPController
 *
 * @author ruoyi
 * @date 2025-01-06
 */
@Api(tags = "课题二：网络IP保护-IP信息管理")
@RestController
@RequestMapping("/equip/info")
public class CombatEquipInfoController extends BaseController {
    @Autowired
    private ICombatEquipInfoService combatEquipInfoService;

    /**
     * 查询网络IP列表
     */
    @ApiOperation(value = "查询网络IP列表")
    @PreAuthorize("@ss.hasPermi('system:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(CombatEquipInfo combatEquipInfo) {
        startPage();
        List<CombatEquipInfo> list = combatEquipInfoService.selectCombatEquipInfoList(combatEquipInfo);
        //list中的beforeRiskDistance是string类型 循环一下将其保留小数点后两位
        for (CombatEquipInfo info : list) {
            if (info.getBeforeRiskDistance() != null) {
                info.setBeforeRiskDistance(String.format("%.2f", Double.parseDouble(info.getBeforeRiskDistance())));
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出网络IP列表
     */
    @ApiOperation(value = "导出网络IP列表")
    @PreAuthorize("@ss.hasPermi('system:info:export')")
    @Log(title = "网络IP", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CombatEquipInfo combatEquipInfo) {
        List<CombatEquipInfo> list = combatEquipInfoService.selectCombatEquipInfoList(combatEquipInfo);
        ExcelUtil<CombatEquipInfo> util = new ExcelUtil<CombatEquipInfo>(CombatEquipInfo.class);
        util.exportExcel(response, list, "网络IP数据");
    }

    /**
     * 获取网络IP详细信息
     */
    @ApiOperation(value = "获取单个网络IP详细信息")
    @PreAuthorize("@ss.hasPermi('system:info:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        CombatEquipInfo combatEquipInfo = combatEquipInfoService.selectCombatEquipInfoById(id);
        if(combatEquipInfo!=null) {
            combatEquipInfo.setBeforeRiskDistance(String.format("%.2f", Double.parseDouble(combatEquipInfo.getBeforeRiskDistance())));
        }
        return success(combatEquipInfo);
    }

    /**
     * 新增网络IP
     */
    @ApiOperation(value = "新增网络IP信息")
    @PreAuthorize("@ss.hasPermi('system:info:add')")
    @Log(title = "网络IP", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CombatEquipInfo combatEquipInfo) {
        combatEquipInfo.setCreateBy(getUsername());
        combatEquipInfo.setCreateTime(new Date());
        combatEquipInfo.setUpdateTime(new Date());
        return toAjax(combatEquipInfoService.insertCombatEquipInfo(combatEquipInfo));
    }

    /**
     * 修改网络IP
     */
    @ApiOperation(value = "修改网络IP信息")
    @PreAuthorize("@ss.hasPermi('system:info:edit')")
    @Log(title = "网络IP", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CombatEquipInfo combatEquipInfo) {
        return toAjax(combatEquipInfoService.updateCombatEquipInfo(combatEquipInfo));
    }

    /**
     * 删除网络IP
     */
    @ApiOperation(value = "删除网络IP信息")
    @PreAuthorize("@ss.hasPermi('system:info:remove')")
    @Log(title = "网络IP", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(combatEquipInfoService.deleteCombatEquipInfoByIds(ids));
    }

    /**
     * 基于虚假地标的抗定位
     */
    @ApiOperation(value = "基于虚假地标的抗定位")
    @PreAuthorize("@ss.hasPermi('system:info:antiPositioning')")
    @Log(title = "网络IP", businessType = BusinessType.OTHER)
    @PostMapping("/antiPositioning")
    public AjaxResult antiPositioning(@RequestBody AntiPositioningInfo antiPositioningInfo) {
        combatEquipInfoService.antiPositioning(antiPositioningInfo);
        return success();
    }

    /**
     * 基于时延混淆的抗定位
     */
    @ApiOperation(value = "基于时延混淆的抗定位")
    @PreAuthorize("@ss.hasPermi('system:info:antiPositioning')")
    @Log(title = "网络IP", businessType = BusinessType.OTHER)
    @PostMapping("/antiPositioningByDelay")
    public AjaxResult antiPositioningByDelay(@RequestBody AntiPositioningInfo antiPositioningInfo) {
        combatEquipInfoService.antiPositioningByDelay(antiPositioningInfo);
        return success();
    }

    /**
     * 设备风险数据统计
     */
    @ApiOperation(value = "设备风险数据统计")
    @PreAuthorize("@ss.hasPermi('system:info:riskDataStatistics')")
    @GetMapping("/riskDataStatistics")
    public AjaxResult riskStatistics() {
        return success(combatEquipInfoService.riskDataStatistics());
    }

    /**
     * 按位置统计设备风险数据
     */
    @ApiOperation(value = "按位置统计设备风险数据")
    @GetMapping("/riskDataByPosition")
    public AjaxResult riskDataByPosition() {
        return success(combatEquipInfoService.riskDataByPosition());
    }

    /**
     * 抗定位回调
     */
    @ApiOperation(value = "抗定位回调")
    @PostMapping("/antiAttributionCallback")
    public AjaxResult antiAttributionCallback(@Validated @RequestBody AntiAttributionCallbackRequest request) {
        combatEquipInfoService.antiAttributionCallback(request);
        return success();
    }

    /**
     * 查询所有虚假IP列表
     */
    @ApiOperation(value = "查询所有虚假IP列表")
    @GetMapping("/fakeIpList")
    public TableDataInfo fakeIpList(CombatFakeIp combatFakeIp) {
        startPage();
        List<CombatFakeIp> combatFakeIps = combatEquipInfoService.selectCombatFakeIpList(combatFakeIp);
        return getDataTable(combatFakeIps);
    }

    /**
     * 虚假IP新增
     */
    @ApiOperation(value = "虚假IP新增")
    @PostMapping("/fakeIpAdd")
    public AjaxResult fakeIpAdd(@Validated @RequestBody CombatFakeIp combatFakeIp) {
        combatEquipInfoService.fakeIpAdd(combatFakeIp);
        return success();
    }

    /**
     * 虚假IP修改
     */
    @ApiOperation(value = "虚假IP修改")
    @PostMapping("/fakeIpEdit")
    public AjaxResult fakeIpEdit(@Validated @RequestBody CombatFakeIp combatFakeIp) {
        combatEquipInfoService.fakeIpEdit(combatFakeIp);
        return success();
    }

    /**
     * 虚假IP删除
     */
    @ApiOperation(value = "虚假IP删除")
    @GetMapping("/fakeIpDel/{id}")
    public AjaxResult fakeIpDel(@NotNull(message = "Id不能为空") @PathVariable Long id) {
        combatEquipInfoService.fakeIpDel(id);
        return success();
    }

    /**
     * 获取文件和标识，导入设备信息
     */
    @ApiOperation(value = "获取文件和标识，导入设备信息")
    @PostMapping("/importEquipInfoData")
    public AjaxResult importEquipInfoData(@RequestPart("file") MultipartFile file, @RequestParam("algorithmMark") String algorithmMark) {
        return success(combatEquipInfoService.importEquipInfoData(file, algorithmMark));
    }

    /**
     * 重新定位
     */
    @ApiOperation(value = "重新定位")
    @PostMapping("/repositioning")
    public AjaxResult repositioning(@RequestBody CombatEquipInfo combatEquipInfo) {
        combatEquipInfoService.repositioning(combatEquipInfo);
        return success();
    }

    /**
     * 设备导入模板下载
     */
    @ApiOperation(value = "设备导入模板文件下载")
    @PostMapping("/download/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 从classpath读取模板文件
        ClassPathResource resource = new ClassPathResource("template/combat_equip_info.xlsx");
        // 检查文件是否存在
        if (!resource.exists()) {
            throw new BaseException("模板文件不存在");
        }
        // 获取文件流
        InputStream inputStream = resource.getInputStream();
        byte[] fileBytes = IOUtils.toByteArray(inputStream);
        inputStream.close();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"combat_equip_info.xlsx\"");
        response.setHeader("Content-Length", String.valueOf(fileBytes.length));
        response.getOutputStream().write(fileBytes);
        response.getOutputStream().flush();
        response.getOutputStream().close();
        return;
    }
}
